package com.ryder.petmatediarybackend.module.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ryder.petmatediarybackend.common.exception.BusinessException;
import com.ryder.petmatediarybackend.module.shop.dto.CreatePetCollectionDTO;
import com.ryder.petmatediarybackend.module.shop.entity.ShopInfo;
import com.ryder.petmatediarybackend.module.shop.entity.ShopPetCollection;
import com.ryder.petmatediarybackend.module.shop.mapper.ShopPetCollectionMapper;
import com.ryder.petmatediarybackend.module.shop.service.ShopInfoService;
import com.ryder.petmatediarybackend.module.shop.service.ShopPetCollectionService;
import com.ryder.petmatediarybackend.module.shop.vo.PetCollectionVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述: 店铺宠物合集表（仅展示，不含交易）(ShopPetCollection)表服务实现类
 * 
 * @author Ryder
 * @version 1.0
 * @since 1.0
 * 更新日期: 2025-10-31
 */
@Slf4j
@Service("shopPetCollectionService")
@RequiredArgsConstructor
public class ShopPetCollectionServiceImpl extends ServiceImpl<ShopPetCollectionMapper, ShopPetCollection> implements ShopPetCollectionService {

    private final ShopInfoService shopInfoService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PetCollectionVO createPetCollection(Long userId, CreatePetCollectionDTO dto) {
        log.info("[创建宠物合集] userId={}, petName={}", userId, dto.getPetName());

        ShopInfo shopInfo = shopInfoService.getShopByUserId(userId);
        if (shopInfo == null) {
            throw new BusinessException("请先创建店铺");
        }

        // 检查数量限制
        long count = this.lambdaQuery().eq(ShopPetCollection::getShopId, shopInfo.getId()).count();
        if (count >= 30) {
            throw new BusinessException("宠物合集最多只能添加30条记录");
        }

        // 验证图片数量
        if (dto.getImages() == null || dto.getImages().isEmpty()) {
            throw new BusinessException("请至少上传一张宠物图片");
        }
        if (dto.getImages().size() > 1) {
            throw new BusinessException("每个宠物合集最多只能上传1张图片");
        }

        ShopPetCollection petCollection = new ShopPetCollection();
        BeanUtil.copyProperties(dto, petCollection);
        petCollection.setShopId(shopInfo.getId());
        petCollection.setImages(JSONUtil.toJsonStr(dto.getImages()));
        petCollection.setStatus(1); // 默认展示中
        petCollection.setAuditStatus(0); // 待审核

        boolean saved = this.save(petCollection);
        if (!saved) {
            throw new BusinessException("创建宠物合集失败");
        }

        log.info("[创建宠物合集成功] petCollectionId={}", petCollection.getId());
        return convertToVO(petCollection);
    }

    @Override
    public List<PetCollectionVO> getMyPetCollections(Long userId) {
        ShopInfo shopInfo = shopInfoService.getShopByUserId(userId);
        if (shopInfo == null) {
            throw new BusinessException("店铺不存在");
        }

        LambdaQueryWrapper<ShopPetCollection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShopPetCollection::getShopId, shopInfo.getId())
                .orderByDesc(ShopPetCollection::getCreateTime);
        
        List<ShopPetCollection> list = this.list(wrapper);
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PetCollectionVO updatePetCollection(Long userId, Long id, CreatePetCollectionDTO dto) {
        log.info("[更新宠物合集] userId={}, id={}", userId, id);

        ShopInfo shopInfo = shopInfoService.getShopByUserId(userId);
        if (shopInfo == null) {
            throw new BusinessException("店铺不存在");
        }

        ShopPetCollection petCollection = this.getById(id);
        if (petCollection == null) {
            throw new BusinessException("宠物合集不存在");
        }

        if (!petCollection.getShopId().equals(shopInfo.getId())) {
            throw new BusinessException("无权修改该宠物合集");
        }

        BeanUtil.copyProperties(dto, petCollection, "id", "shopId");
        if (dto.getImages() != null) {
            petCollection.setImages(JSONUtil.toJsonStr(dto.getImages()));
        }

        boolean updated = this.updateById(petCollection);
        if (!updated) {
            throw new BusinessException("更新宠物合集失败");
        }

        log.info("[更新宠物合集成功] id={}", id);
        return convertToVO(petCollection);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePetCollection(Long userId, Long id) {
        log.info("[删除宠物合集] userId={}, id={}", userId, id);

        ShopInfo shopInfo = shopInfoService.getShopByUserId(userId);
        if (shopInfo == null) {
            throw new BusinessException("店铺不存在");
        }

        ShopPetCollection petCollection = this.getById(id);
        if (petCollection == null) {
            throw new BusinessException("宠物合集不存在");
        }

        if (!petCollection.getShopId().equals(shopInfo.getId())) {
            throw new BusinessException("无权删除该宠物合集");
        }

        boolean deleted = this.removeById(id);
        if (!deleted) {
            throw new BusinessException("删除宠物合集失败");
        }

        log.info("[删除宠物合集成功] id={}", id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Long userId, Long id, Integer status) {
        log.info("[更新宠物状态] userId={}, id={}, status={}", userId, id, status);

        ShopInfo shopInfo = shopInfoService.getShopByUserId(userId);
        if (shopInfo == null) {
            throw new BusinessException("店铺不存在");
        }

        ShopPetCollection petCollection = this.getById(id);
        if (petCollection == null) {
            throw new BusinessException("宠物合集不存在");
        }

        if (!petCollection.getShopId().equals(shopInfo.getId())) {
            throw new BusinessException("无权修改该宠物合集");
        }

        petCollection.setStatus(status);
        boolean updated = this.updateById(petCollection);
        if (!updated) {
            throw new BusinessException("更新宠物状态失败");
        }

        log.info("[更新宠物状态成功] id={}", id);
    }

    @Override
    public List<PetCollectionVO> getByShopId(Long shopId) {
        log.info("[查询店铺宠物合集] shopId={}", shopId);
        
        LambdaQueryWrapper<ShopPetCollection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShopPetCollection::getShopId, shopId)
                .eq(ShopPetCollection::getStatus, 1) // 只查询展示中的
                .eq(ShopPetCollection::getAuditStatus, 1) // 只查询审核通过的
                .orderByDesc(ShopPetCollection::getCreateTime);
        
        List<ShopPetCollection> list = this.list(wrapper);
        log.info("[查询店铺宠物合集成功] shopId={}, 数量={}", shopId, list.size());
        
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    private PetCollectionVO convertToVO(ShopPetCollection petCollection) {
        PetCollectionVO vo = new PetCollectionVO();
        BeanUtil.copyProperties(petCollection, vo);

        if (petCollection.getImages() != null) {
            vo.setImages(JSONUtil.toList(petCollection.getImages(), String.class));
        }

        vo.setPetTypeText(getPetTypeText(petCollection.getPetType()));
        vo.setGenderText(getGenderText(petCollection.getGender()));
        vo.setStatusText(getStatusText(petCollection.getStatus()));
        vo.setAuditStatusText(getAuditStatusText(petCollection.getAuditStatus()));

        return vo;
    }

    private String getPetTypeText(Integer petType) {
        if (petType == null) return "未知";
        return switch (petType) {
            case 1 -> "猫";
            case 2 -> "狗";
            case 3 -> "其他";
            default -> "未知";
        };
    }

    private String getGenderText(Integer gender) {
        if (gender == null) return "未知";
        return switch (gender) {
            case 1 -> "公";
            case 2 -> "母";
            default -> "未知";
        };
    }

    private String getStatusText(Integer status) {
        if (status == null) return "未知";
        return switch (status) {
            case 1 -> "展示中";
            case 2 -> "已下架";
            default -> "未知";
        };
    }

    private String getAuditStatusText(Integer auditStatus) {
        if (auditStatus == null) return "未知";
        return switch (auditStatus) {
            case 0 -> "待审核";
            case 1 -> "审核通过";
            case 2 -> "审核驳回";
            default -> "未知";
        };
    }
}
